package com.hzpd.hainan.module.video.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.ToolBarActivity;
import com.hzpd.hainan.model.base.BaseEntity;
import com.hzpd.hainan.model.news.CommenEntity;
import com.hzpd.hainan.model.news.CommentBean;
import com.hzpd.hainan.model.news.IsCollectionEntity;
import com.hzpd.hainan.model.usercenter.EmptyEntityList;
import com.hzpd.hainan.model.video.VideoDetialEntity;
import com.hzpd.hainan.model.video.VideoItemBean;
import com.hzpd.hainan.model.video.VideoItenEntity;
import com.hzpd.hainan.module.news.adapter.CommentAdapter;
import com.hzpd.hainan.module.news.adapter.ListDataSetObserver;
import com.hzpd.hainan.module.news.dialog.InputPop;
import com.hzpd.hainan.module.video.utils.VideoPlayerHelper;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.DeviceUtils;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.PageCtrl;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;
import com.hzpd.hainan.wxapi.SharedUtil;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/20.
 */

public class VideoDetailActivity extends ToolBarActivity {

    @BindView(R.id.img_bg_id)
    ImageView imgBgId;
    @BindView(R.id.img_play_id)
    ImageView imgPlayId;
    @BindView(R.id.rl_id)
    RelativeLayout rlId;
    @BindView(R.id.video_title_tx)
    TextView videoTitleTx;
    @BindView(R.id.from_iv)
    ImageView fromIv;
    @BindView(R.id.videoinfo_ll)
    LinearLayout videoinfoLl;
    @BindView(R.id.comment_ll)
    ListView commentLl;
    @BindView(R.id.comment_sv)
    PullToRefreshScrollView commentSv;


    @BindView(R.id.news_detail_bak)
    LinearLayout newsDetailBak;
    @BindView(R.id.et_pinglun_id)
    EditText etPinglunId;
    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;
    @BindView(R.id.newdetail_comments)
    RelativeLayout newdetailComments;
    @BindView(R.id.xf_newshtmldetail_iv_collection)
    ImageView xfNewshtmldetailIvCollection;
    @BindView(R.id.rl_newdetail_collection)
    RelativeLayout rlNewdetailCollection;
    @BindView(R.id.newdetail_share)
    RelativeLayout newdetailShare;
    @BindView(R.id.news_detail_ll_bottom1)
    LinearLayout newsDetailLlBottom1;
    private VideoItemBean itemBean;
    private VideoItemBean itemDetialBean;
    private InputPop inputPop;
    private final int  PAGE_SIZE = 15;
    private int page = 1;
    private CommentAdapter commAdapter;
    boolean isClear = true;

    @Override
    public String initToolBarTitle() {
        return null;
    }

    @Override
    public int setMyContentView() {
        return R.layout.activity_video_detail;
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        String from = intent.getStringExtra("from");
        itemBean = (VideoItemBean) intent.getSerializableExtra("videoItemBean");
        getDetialVideo();

        videoTitleTx.setText(itemBean.getTitle());
        Glide.with(this).load(itemBean.getMainpic()).placeholder(R.drawable.default_bg).crossFade().into(imgBgId);
        rlId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                VideoPlayerHelper.getInstance().play(rlId, itemBean.getVideourl(), 0);
            }
        });

        isCollection();
        getCommentList();
        commAdapter  = new CommentAdapter(activity,0);
        commAdapter.registerDataSetObserver(new ListDataSetObserver(commentLl));
        commentLl.setAdapter(commAdapter);
        commentLl.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (!"0".equals(itemBean.getComflag())) {
                    CommentBean cb = (CommentBean) commAdapter.getItem(position);
                    popCommentActivity(cb);
                }
            }
        });
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.news_detail_bak, R.id.rl_newdetail_collection, R.id.newdetail_share,R.id.et_pinglun_id})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.news_detail_bak:
                this.finish();
                break;
            case R.id.rl_newdetail_collection:
                if (spu.getUser()!=null){
                    addCollection();
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.et_pinglun_id:
                if (spu.getUser()!=null){
                    popCommentActivity(null);
                }else{
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.newdetail_share:
                String imgurl = null;
                imgurl = itemDetialBean.getMainpic();
                SharedUtil.showShares(true, null, itemDetialBean.getTitle(), itemDetialBean.getNewsurl(), imgurl, activity);
                break;
        }
    }

    //评论弹窗
    private void popCommentActivity(final CommentBean commentBean){
        if (!"0".equals(itemBean.getComflag())) {
            if (inputPop == null){
                inputPop = new InputPop(activity, new InputPop.InputListener() {
                    @Override
                    public void inputstr(String string) {
                        if (commentBean != null) {
                            sendComment(string, commentBean.getCid());
                        }else {
                            sendComment(string, null);
                        }
                    }
                });
            }
            inputPop.setFocusable(true);
            inputPop.showAtLocation(findViewById(R.id.root_ll), Gravity.BOTTOM,0,0);
        } else {
            TUtils.toast("该条新闻不可评论");
        }
    }
    //发表评论接口
    private void sendComment(String content,String cid){
        showDialog();
        Map<String, String> map = new HashMap<>();
        map.put("nid", itemBean.getVid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "3");
        map.put("content", content);
        map.put("cid", cid);
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsComment(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<BaseEntity, Boolean>() {
                    @Override
                    public Boolean call(BaseEntity entity) {
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity entity) {
                        disMissDialog();
                        if ("200".equals(entity.code)){
                            etPinglunId.setText("");
                        }else{
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        TUtils.toast("评论失败");
                        disMissDialog();
                    }
                });
    }
    //是否收藏
    private void isCollection() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser()==null){
            return;
        }
        map.put("typeid", itemBean.getVid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", "3");
        Factory.provideHttpService()
                .newsIsCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)){
                            if ("1".equals(entity.data.getStatus())){
                                xfNewshtmldetailIvCollection.setImageResource(R.drawable.zqzx_collection);
                            }
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    public  void addVisits(){
        Map<String,String> map=new HashMap<>();
        map.put("nid",itemBean.getNid());
        map.put("type","3");
        map.put("siteid",InterfaceJsonfile.SITEID);
        map.put("num","1");
        map.put("tid",itemDetialBean.getVid());
        if (spu.getUser()!=null){
            map.put("uid",spu.getUser().getUid());
        }

        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().addvisit(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntityList) {
                        return true;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntityList) {
                        LogUtils.i("emptyEntityList----"+emptyEntityList.code);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }
    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", itemBean.getVid());
        map.put("uid",spu.getUser().getUid());
        map.put("type", "3");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)){
                            if ("1".equals(entity.data.getStatus())){
                                TUtils.toast("收藏成功");
                                xfNewshtmldetailIvCollection.setImageResource(R.drawable.zqzx_collection);
                            } else {
                                xfNewshtmldetailIvCollection.setImageResource(R.drawable.zqzx_nd_collection);
                                TUtils.toast("收藏取消");
                            }
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    private void getDetialVideo(){
        Map<String,String> map=new HashMap<>();
        map.put("vid",itemBean.getVid());
        Factory.provideHttpService().getvideoinfo(map)
                 .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<VideoDetialEntity, Boolean>() {
                    @Override
                    public Boolean call(VideoDetialEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<VideoDetialEntity>() {
                    @Override
                    public void call(VideoDetialEntity entity) {
                        if ("200".equals(entity.code)){
                            itemDetialBean=entity.data;
                            addVisits();
                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                        Glide.with(VideoDetailActivity.this).load(itemDetialBean.getMainpic()).placeholder(R.drawable.default_bg).crossFade().into(imgBgId);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }


    //获取评论列表
    private void getCommentList(){
        Map<String, String> map = new HashMap<>();
        map.put("nid", itemBean.getVid());
        map.put("type", "3");
        map.put("Page", page+"");
        map.put("PageSize", PAGE_SIZE+"");
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsCommentList(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<CommenEntity, Boolean>() {
                    @Override
                    public Boolean call(CommenEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CommenEntity>() {
                    @Override
                    public void call(CommenEntity entity) {
                        if ("200".equals(entity.code)){
                            commentLl.setVisibility(View.VISIBLE);
                            commAdapter.appendData(entity.data, isClear);
                            commAdapter.notifyDataSetChanged();
                            //------+
                            //----
                            if (entity.data.size() < PAGE_SIZE) {
                                commentSv.setMode(PullToRefreshBase.Mode.DISABLED);
                            } else {
                                commentSv.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                            }

                        }else{
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }
    @Override
    public void finish() {
        VideoPlayerHelper.getInstance().stop();
        super.finish();
    }
}
